#include "gaitFiles.h"
#include <unistd.h>
#include <fstream>

gaitFiles::gaitFiles()
{
    //ctor
    steps=0;

}
gaitFiles::gaitFiles(string a)
{
    //ctor
    filename =a;
    steps=0;

}
bool gaitFiles::load( string name)
{
    std::ifstream f(name.c_str());
    if(!f)
        return false;
     while(!f.eof())
  {
    int *p=new int[21];
    for(int i=0;i<21;i++)
    {
        int t;f>>t;
        p[i]=t;
    }
    gaitArray.push_back(p);
    steps++;
  }
    return true;

}
gaitFiles::~gaitFiles()
{
    //dtor
    save();
    for(int i=0;i<gaitArray.size();i++)
        delete [] gaitArray[i];
    steps=0;

}
void gaitFiles::run(double step,int *data)
{
    int t=step*steps;
    for(int i=0;i<20;i++)
        data[i]=gaitArray[t][i];
    usleep(gaitArray[t][20]);
}
void gaitFiles::add(int *data)
{
    struct timeval now;
    gettimeofday(&now, NULL);
    if(steps>0)

    {
        int dt=(now.tv_sec-time1.tv_sec)*1000+(now.tv_usec-time1.tv_usec)/1000;
        //usec
        gaitArray[steps-1][20]=dt;
    }
    time1=now;
    int *p=new int[21];
    for(int i=0;i<20;i++)
    {

        p[i]=data[i];
    }
    p[20]=0;
    gaitArray.push_back(p);
    steps++;
}
void gaitFiles::save()
{

    std::ofstream fout(filename.c_str());
    for(int j=0;j<gaitArray.size();j++)
    {


    for(int i=0;i<21;i++)
    {
        fout<<gaitArray[j][i]<<" ";
    }
    fout<<std::endl;
    }

}
